package jwt

import (
	"log"
	"net/http"
	"strconv"

	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/e"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/util"
	"github.com/gin-gonic/gin"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}

		code = e.SUCCESS
		token := c.Request.Header.Get("authorization")
		var userID uint64
		if token == "" {
			log.Println("token not in header")
			code = e.INVALID_PARAMS
		} else {
			claims, err := util.ParseToken(token)
			if err != nil {
				log.Println(err)
				code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
			} else {
				userID, err = strconv.ParseUint(claims.UserId, 10, 64)
				if err != nil {
					log.Println(err)
					code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
				}
			}
		}
		if code != e.SUCCESS {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  e.GetMsg(code),
				"data": data,
			})
			c.Abort()
			return
		}
		c.Set("userID", userID)
		c.Next()
	}
}
